package com.xinchao.ck_mips.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import com.orhanobut.logger.Logger;

import java.util.Calendar;
import java.util.Date;


/**
 * @author: JessieKate
 * @date: 2018/10/25
 * @email: lyj1246505807@gmail.com
 * @description: 闹钟设置工具类
 */

public class AlarmManagerUtil {
    public static final String ALARM_ACTION = "com.xinchao.ckmips.clock";

    /**
     * 设置闹钟
     * @param context
     * @param intent 接收器返回的intent
     */
    public static void setAlarmTime(Context context, Intent intent) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent sender = PendingIntent.getBroadcast(context, intent.getIntExtra("id", 0),
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        int interval = (int) intent.getLongExtra("intervalMillis", 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            long nextTime = System.currentTimeMillis() + interval;
            // 设置下一次运行时间
            am.setExact(AlarmManager.RTC_WAKEUP,nextTime, sender);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date(nextTime));
            Logger.d("next alarm:  year" + calendar.get(Calendar.YEAR)
                    + "    month:" + calendar.get(Calendar.MONTH)
                    + "    day" + calendar.get(Calendar.DAY_OF_MONTH)
                    + "    hour" + calendar.get(Calendar.HOUR_OF_DAY)
                    + "    minute:" +calendar.get(Calendar.MINUTE));
        }
    }

    /**
     * 取消闹钟
     * @param context
     * @param action
     * @param id
     */
    public static void cancelAlarm(Context context, String action, int id) {
        Intent intent = new Intent(action);
        PendingIntent pi = PendingIntent.getBroadcast(context, id, intent, PendingIntent
                .FLAG_CANCEL_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pi);
    }
    /**
     * @param flag            周期性时间间隔的标志,flag = 0 表示一次性的闹钟, flag = 1 表示每天提醒的闹钟(1天的时间间隔),flag = 2
     *                        表示按周每周提醒的闹钟（一周的周期性时间间隔）
     * @param hour            时
     * @param minute          分
     * @param id              闹钟的id
     * @param week            week=0表示一次性闹钟或者按天的周期性闹钟，非0 的情况下是几就代表以周为周期性的周几的闹钟
     * @param tips            闹钟提示信息
     */
    public static void setAlarm(Context context, int flag, int hour, int minute, int id, int
            week, String tips) {
        if(id == 0){
            Logger.d("setting screen on ---->" + "hour:" + hour + "/minute:" + minute);
        }else{
            Logger.d("setting screen off ---->" + "hour:" + hour + "/minute:" + minute);
        }

        // 获取闹钟管理器实例
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        // 获取日历实例
        Calendar calendar = Calendar.getInstance();
        // 间隔时间
        long intervalMillis = 0;
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        // 一次性闹钟
        if (flag == 0) {
            intervalMillis = 0;
        }
        // 每天闹钟
        else if (flag == 1) {
            intervalMillis = 24 * 3600 * 1000;
        }
        // 每周闹钟
        else if (flag == 2) {
            intervalMillis = 24 * 3600 * 1000 * 7;
        }
        // 初始化发送数据包，放入间隔时间，提醒内容，id，提醒方式
        Intent intent = new Intent(ALARM_ACTION);
        intent.putExtra("intervalMillis", intervalMillis);
        intent.putExtra("msg", tips);
        intent.putExtra("id", id);

        //  FLAG_CANCEL_CURRENT 当需要获取的PendingIntent对象已经存在时，先取消当前的对象，再获取新的；
        // 	FLAG_ONE_SHOT 获取的PendingIntent对象只能使用一次，再次使用需要重新获取
        // 	FLAG_NO_CREATE 如果获取的PendingIntent对象不存在，则返回null
        //	FLAG_UPDATE_CURRENT 如果只是Intent附加的数据不同，那么当前存在的PendingIntent对象不会被取消，而是重新加载新的Intent附加的数据
        PendingIntent sender = PendingIntent.getBroadcast(context, id, intent, PendingIntent
                .FLAG_CANCEL_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 判断当前提醒时间是否已过
            long timeLong = calMethod(week, calendar.getTimeInMillis());
            am.setExact(AlarmManager.RTC_WAKEUP, timeLong, sender);
        } else {
            if (flag == 0) {
                am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
            } else {
                am.setRepeating(AlarmManager.RTC_WAKEUP, calMethod(week, calendar.getTimeInMillis
                        ()), intervalMillis, sender);
            }
        }
    }

    /**
     * @param weekflag 传入的是周几
     * @param dateTime 传入的是时间戳（设置当天的年月日+从选择框拿来的时分秒）
     * @return 返回起始闹钟时间的时间戳
     */
    private static long calMethod(int weekflag, long dateTime) {
        long time = 0;
        //weekflag == 0表示是按天为周期性的时间间隔或者是一次行的，weekflag非0时表示每周几的闹钟并以周为时间间隔
        if (weekflag != 0) {
            Calendar c = Calendar.getInstance();
            int week = c.get(Calendar.DAY_OF_WEEK);
            if (1 == week) {
                week = 7;
            } else if (2 == week) {
                week = 1;
            } else if (3 == week) {
                week = 2;
            } else if (4 == week) {
                week = 3;
            } else if (5 == week) {
                week = 4;
            } else if (6 == week) {
                week = 5;
            } else if (7 == week) {
                week = 6;
            }

            if (weekflag == week) {
                if (dateTime > System.currentTimeMillis()) {
                    time = dateTime;
                } else {
                    time = dateTime + 7 * 24 * 3600 * 1000;
                }
            } else if (weekflag > week) {
                time = dateTime + (weekflag - week) * 24 * 3600 * 1000;
            } else if (weekflag < week) {
                time = dateTime + (weekflag - week + 7) * 24 * 3600 * 1000;
            }
        } else {
            if (dateTime > System.currentTimeMillis()) {
                time = dateTime;
            } else {
                time = dateTime + 24 * 3600 * 1000;
            }
        }
        return time;
    }
}
